package com.wei.service_vod.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.aliyuncs.vod.model.v20170321.DeleteVideoResponse;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.wei.service_base.exception.XueYuanException;
import com.wei.service_vod.service.VodService;
import com.wei.service_vod.util.ConstantPropertiesUtil;
import com.wei.service_vod.util.InitObject;
import com.wei.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * @author wjx
 * @ClassName VodController
 * @description: TODO
 * @date 2022-11-30 22:47
 * @version: 1.0
 */
@RestController
@RequestMapping("/eduvod/video")
public class VodController {

    @Autowired
    private VodService vodService;

    @PostMapping("/uploadVideo")
    private R uploadVideo(MultipartFile file) {

        String videoSourceId = vodService.uploadToAliyun(file);

        return R.ok().data("videoSourceId", videoSourceId);
    }

    @DeleteMapping("/removeVideo/{videoId}")
    public R removeVideo(@PathVariable String videoId) throws ClientException {
        try {
            DefaultAcsClient client = InitObject.initVodClient(ConstantPropertiesUtil.KEY_ID, ConstantPropertiesUtil.KEY_SECRET);

            DeleteVideoRequest request = new DeleteVideoRequest();
            request.setVideoIds(videoId);
            DeleteVideoResponse response = client.getAcsResponse(request);
            return R.ok();
        } catch (ClientException e) {
            throw new XueYuanException(20001, "删除视频失败");
        }


    }

    @DeleteMapping("/deleteBatch")
    public R deleteBatch(@RequestParam("vidList") List<String> vidList) {

        vodService.removeBatch(vidList);

        return R.ok();
    }

    /**
     * 根据videoId获取视频凭证
     *
     * @param videoId
     * @return
     */
    @GetMapping("/getPlayAuth/{videoId}")
    public R getPlayAuth(@PathVariable String videoId) {

        System.out.println(videoId);
        try {
            //创建初始化对象
            DefaultAcsClient client = InitObject.initVodClient(ConstantPropertiesUtil.KEY_ID, ConstantPropertiesUtil.KEY_SECRET);

            //创建获取视频凭证的request和response
            GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();

            // 向request对象里面设置视频id
            request.setVideoId(videoId);

            //调用初始化对象的方法得到凭证
            GetVideoPlayAuthResponse response = client.getAcsResponse(request);

            //播放凭证
            return R.ok().data("playAuth", response.getPlayAuth());
        } catch (ClientException e) {
            e.printStackTrace();
            throw new XueYuanException(20001, "获取凭证失败");
        }
    }
}
